package com.edu.dk.security.impl;

import javax.servlet.ServletException;

import com.edu.dk.security.WebContext;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * 对输入、输出的数据进行安全检查，排除可能的攻击。例如：XSS过滤、CRLF换行回车过滤等。
 * 
 * 
 */
public class BasicFilter extends AbstractFilter {

	private Object[] interceptors;// 拦截器列表

	private String maxCookieSize = "10k";// 最大Cookie的大小

	private Pattern urlPattern = Pattern.compile("/*");

	public void setInterceptors(Object[] interceptors) {
		this.interceptors = interceptors;
	}

	public void setMaxCookieSize(String maxCookieSize) {
		this.maxCookieSize = maxCookieSize;
	}

	@Override
	protected void initContext(WebContext context) {
		((BasicWebContextImpl) context).initContext(interceptors);
	}

	@Override
	public boolean isMatch(String url) {
		Matcher matcher = urlPattern.matcher(url);
		if (matcher.matches()) {
			return true;
		}
		return false;
	}

	@Override
	public void preProcess(WebContext context) throws ServletException, IOException {
		BasicWebContextImpl basic = (BasicWebContextImpl) context;
		basic.prepareResponse();
	}

	@Override
	public void postProcess(WebContext context) throws ServletException, IOException {
		BasicWebContextImpl basic = (BasicWebContextImpl) context;
		basic.commitResponse();
	}

	@Override
	public WebContext getAlreadyWrappedContext(WebContext wrappedContext) {
		BasicWebContextImpl basic = new BasicWebContextImpl(wrappedContext);
		basic.setMaxCookieSize(maxCookieSize);
		return basic;
	}

	public int getOrder() {
		return 1;
	}

}
